@page "/admin/blogs/editor/{Slug?}"
@using System.Text;

@inject HttpClient _httpClient
@inject IStringLocalizer<Resource> _localizer
@inject NavigationManager _navigation
@inject IToaster _toaster
@inject ToasterService _toasterService

<PageTitleComponent Title="@_localizer["new-post"]" />
<PostEditorComponent @ref="_postEditorComponent" Post="@Post" OnSaveCallback="OnSaveAsync" OnRemoveCallback="OnRemoveAsync" />

@code {

  [Parameter] public string? Slug { get; set; }

  private PostEditorComponent _postEditorComponent = default!;

  protected PostEditorDto Post { get; set; } = new PostEditorDto
    {
      Title = string.Empty,
      Description = string.Empty,
      Content = string.Empty,
      PostType = PostType.Post,
      Categories = new List<CategoryDto>(),
    };

  protected override async Task OnParametersSetAsync()
  {
    if (!string.IsNullOrEmpty(Slug))
    {
      Post = (await _httpClient.GetFromJsonAsync<PostEditorDto>($"api/post/byslug/{Slug}"))!;
      if (Post.Categories == null) Post.Categories = new List<CategoryDto>();
      await _postEditorComponent.SetPostInfoAsync(Post);
    }
  }

  protected async Task OnSaveAsync(PostEditorDto post)
  {
    if (post.Id == 0)
    {
      var response = await _httpClient.PostAsJsonAsync($"api/post/add", post);
      if (_toasterService.CheckResponse(response))
      {
        var slug = await response.Content.ReadAsStringAsync();
        _navigation.NavigateTo($"/admin/blogs/editor/{slug}");
      }
    }
    else
    {
      var response = await _httpClient.PutAsJsonAsync($"api/post/update", post);
      _toasterService.CheckResponse(response);
    }
  }

  protected async Task OnRemoveAsync(int id)
  {
    var result = await _httpClient.DeleteAsync($"api/post/{id}");
    if (result.IsSuccessStatusCode) _toaster.Success(_localizer["completed"]);
    else _toaster.Error(_localizer["generic-error"]);
    _navigation.NavigateTo("admin");
  }
}
